<?php
/**
 * Controller_Order
*
* Класс Controller_Order отвечает за обработку заказов
*
*/
class Controller_Test extends Controller_Base {
	/**
	 * Выбор действия по URL
	 *
	 */
	public function action() {
		Service_Debug::setDebug();
		$objSession = User_Session::instance();
		switch ($this->arrRequest[1]) {
			case '': 
				$this->actionTest();
				break;
			case 'k':
				$this->actionTestK();
				break;
			default:
				throw new Exception_SiteError('', 404);
				break;
		}
	}
	
	public function actionTest() {
		$objDB = Service_Database::instance();
		$objCurl = new Service_Curl();
		$url = 'http://maps.googleapis.com/maps/api/geocode/json';
		
		$arrParams = array(
				'region' => 'ru',
				'language' => 'ru',
				'sensor' => 'false'
		);
		$what = '`finist`.`ID_finist` <= 8600 AND `finist`.`ID_finist` >= 8000';
		
		$stmt = "SELECT `finist`.`ID_finist`,`finist`.`place_start`,`finist`.`place_start_latitude` FROM `finist` WHERE" . $what . ""; 
		$ordersArray = $objDB->select($stmt);
		for($j = 0; $j < count($ordersArray); $j++) {
			sleep(1.3);
			$objCity = new City();
			$arrParams['address'] = str_replace (array('&quot;','ЛО','Сб'), array('','Ленинградская область,','Спб'), $ordersArray[$j]['place_start']);
			if($ordersArray[$j]['place_start_latitude']) continue;
			$result = $objCurl->httpRequest('GET', $url, $arrParams, false);
			$result = json_decode($result);
			
			echo '<pre>';
			
			echo '</pre>';
			if($result->status == 'OK' && !empty($result->results[0])) {
				
				$firstItemArr = $result->results[0]->address_components;
				$addressString = $result->results[0]->formatted_address;
				$cityName = '';
				$neight = '';
				$name = '';
				for($i = 0; $i < count($firstItemArr); $i++) {
					if($i == 0  && in_array('neighborhood', $firstItemArr[$i]->types) && in_array('political', $firstItemArr[$i]->types)) $neight = $firstItemArr[$i]->long_name;
					if(in_array('locality', $firstItemArr[$i]->types) && in_array('political', $firstItemArr[$i]->types) ) $cityName = $firstItemArr[$i]->long_name;
					if(in_array('political', $firstItemArr[$i]->types) && in_array('administrative_area_level_1', $firstItemArr[$i]->types)) $tempName = $firstItemArr[$i]->long_name;
				}
				
				$name = $neight != '' ? $neight : $cityName;
				if(!$name) $name = $tempName;
				$name = str_replace(array('п. ','г. ','город '), array('','',''), $name);
				
				$cityId = $objCity->getIdByName($name);
				$latitude = $result->results[0]->geometry->location->lat;
				$longitude = $result->results[0]->geometry->location->lng;
				
				if($name == '') continue;
				if(!$cityId) {
					$objCity->setFields(array('city_name' => $name , 'from_finist' => 1, 'latitude' => $latitude, 'longitude' => $longitude));
					if(!$objCity->save()) echo 'error ' . $neight . '<br>';
					else {
						echo 'OK ' . $name . '<br>';
						$cityId = $objCity->id;
					}
				}
				
				$updateArr = array (
						'ID_place_start' => $cityId,
						'place_start_latitude' => $latitude,
						'place_start_longitude' => $longitude,
						'place_start_address' => $addressString
						);
				//print_r($updateArr);
				$objDB->update('finist', $updateArr, array('ID_finist' => $ordersArray[$j]['ID_finist']));
			}
			elseif($result->status == 'OVER_QUERY_LIMIT') {
				echo 'BAN';
				exit();
			}
		}
		
		$stmt = "SELECT `finist`.`ID_finist`,`finist`.`place_finish`,`finist`.`place_finish_latitude` FROM `finist` WHERE " . $what . "";
		$ordersArray = $objDB->select($stmt);
		for($j = 0; $j < count($ordersArray); $j++) {
			sleep(1.3);
			$objCity = new City();
			$arrParams['address'] = str_replace (array('&quot;','ЛО','Сб'), array('','Ленинградская область,','Спб'), $ordersArray[$j]['place_finish']);
			if($ordersArray[$j]['place_finish_latitude']) continue;
			$result = $objCurl->httpRequest('GET', $url, $arrParams, false);
			$result = json_decode($result);
			echo '<pre>';
			//print_r($result);
			//echo '</pre>';
			if($result->status == 'OK' && !empty($result->results[0])) {
		
				$firstItemArr = $result->results[0]->address_components;
				$addressString = $result->results[0]->formatted_address;
				$cityName = '';
				$neight = '';
				$name = '';
				for($i = 0; $i < count($firstItemArr); $i++) {
					if(in_array('neighborhood', $firstItemArr[$i]->types) && in_array('political', $firstItemArr[$i]->types)) $neight = $firstItemArr[$i]->long_name;
					if(in_array('locality', $firstItemArr[$i]->types) && in_array('political', $firstItemArr[$i]->types) ) $cityName = $firstItemArr[$i]->long_name;
					if(in_array('political', $firstItemArr[$i]->types) && in_array('administrative_area_level_1', $firstItemArr[$i]->types)) $tempName = $firstItemArr[$i]->long_name;
				}
				$name = $neight != '' ? $neight : $cityName;
				if(!$name) $name = $tempName;
					$name = str_replace(array('п. ','г. ','город '), array('','',''), $name);

				$cityId = $objCity->getIdByName($name);
				$latitude = $result->results[0]->geometry->location->lat;
				$longitude = $result->results[0]->geometry->location->lng;
				
				if($name == '') continue;
				if(!$cityId) {
					$objCity->setFields(array('city_name' => $name , 'from_finist' => 1, 'latitude' => $latitude, 'longitude' => $longitude));
					if(!$objCity->save()) echo 'error ' . $name . '<br>';
					else {
						echo 'OK ' . $name . '<br>';
						$cityId = $objCity->id;
					}
				}
		
				$updateArr = array (
						'ID_place_finish' => $cityId,
						'place_finish_latitude' => $latitude,
						'place_finish_longitude' => $longitude,
						'place_finish_address' => $addressString
				);
				//print_r($updateArr);
				$objDB->update('finist', $updateArr, array('ID_finist' => $ordersArray[$j]['ID_finist']));
			}
			elseif($result->status == 'OVER_QUERY_LIMIT') {
				echo 'BAN';
				exit();
			}
		}
	}
	
	public function actionTestK () {
		$objDB = Service_Database::instance();
		$stmt = "SELECT `finist`.`ID_finist`,`route`.`distance`
				FROM `finist`
				INNER JOIN `route`
				ON (`finist`.`ID_place_start`=`route`.`ID_one_city` AND `finist`.`ID_place_finish`=`route`.`ID_another_city`) OR (`finist`.`ID_place_start`=`route`.`ID_another_city` AND `finist`.`ID_place_finish`=`route`.`ID_one_city`)";
			$result = $objDB->select($stmt);
			
			foreach($result as $orderArr) {
				$stmt = "UPDATE `finist`
						SET `finist`.`route_distance`='" . $orderArr['distance'] . "' WHERE `finist`.`ID_finist`='" . $orderArr['ID_finist'] . "'";
				$objDB->query($stmt);
			}
			
	}
}
?>